package cn.stylefeng.guns.core.schedue.jobs;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.HttpRequest;
import cn.stylefeng.guns.core.module.OrderStatus;
import cn.stylefeng.guns.modular.manager.entity.FlowOrder;
import cn.stylefeng.guns.modular.manager.entity.FlowPayInfo;
import cn.stylefeng.guns.modular.manager.mapper.FlowPayInfoMapper;
import cn.stylefeng.guns.modular.manager.service.FlowOrderService;
import cn.stylefeng.guns.modular.manager.service.FlowPayInfoService;
import cn.stylefeng.guns.utils.douyin.*;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class OrderPayStatusQueryTask {

    @Resource
    public FlowPayInfoService flowPayInfoService;

    @Resource
    public FlowPayInfoMapper flowPayInfoMapper;

    @Resource
    public  FlowOrderService flowOrderService;



    //每分钟轮询支付状态
    @Scheduled(cron = "0 0/1 * * * ? ")
    public void pullOrederPayStatus(){
        log.info("pullOrederPayStatus，定时拉取支付状态 = {}", 0);



        List<FlowPayInfo> flowPayInfos = flowPayInfoMapper.selectList(Wrappers.<FlowPayInfo>query().lambda()
                //0未支付 1已支付 2支付已取消
                .eq(FlowPayInfo::getPayStatus, 0)
                .eq(FlowPayInfo::getPayType, 3)
                .gt(FlowPayInfo::getMoneys, 0)
                .isNull(FlowPayInfo::getTradeNo)
        );

        if(CollectionUtil.isNotEmpty(flowPayInfos)){
             for (FlowPayInfo info : flowPayInfos){
                     queryPayResult(info);
             }
        }

    }




    /**
     * 回调用已支付
     *
     * @param payCode           支付代码
     * @param thirdPartyPayCode 第三方支付代码
     */
    private void callbackPayed(String payCode,String thirdPartyPayCode){

        //此处做自己的业务处理
        //查询订单
        QueryWrapper<FlowPayInfo> flowPayInfoQueryWrapper = new QueryWrapper<>();
        flowPayInfoQueryWrapper.eq("pay_code",payCode);
        flowPayInfoQueryWrapper.last("limit 1");
        FlowPayInfo flowPayInfo = flowPayInfoService.getOne(flowPayInfoQueryWrapper);
        if(flowPayInfo != null&&   StringUtils.isBlank(flowPayInfo.getTradeNo())){
            flowPayInfo.setTradeNo(thirdPartyPayCode);
            flowPayInfo.setUpdateTime(new Date());
            flowPayInfo.setPayTime(new Date());
            flowPayInfo.setPayStatus(OrderStatus.IsPay);
            flowPayInfoService.updateById(flowPayInfo);
            //更新订单
            QueryWrapper<FlowOrder> flowOrderQueryWrapper = new QueryWrapper<>();
            flowOrderQueryWrapper.eq("order_id",flowPayInfo.getOrderId());
            flowOrderQueryWrapper.last("limit 1");
            FlowOrder flowOrder = flowOrderService.getOne(flowOrderQueryWrapper);
            if(flowOrder != null) {
                if (flowOrder.isDepositPay() == 1) {
                    flowOrder.setDepositPayCode(payCode);
                    flowOrder.setDepositPay(0l);
                    flowOrderService.updateById(flowOrder);
                } else {
                    flowOrder.setOrderStatus(OrderStatus.OrderWaitService);
                    flowOrder.setPayStatus(OrderStatus.IsPay);
                    flowOrder.setPayCode(payCode);
                    flowOrderService.updateById(flowOrder);
                }

            }
        }
    }



    public   void queryPayResult ( FlowPayInfo payInfo ){

        Map<String, Object> testCase = new HashMap<String, Object>() {
            {
                put("app_id", DouyinConfig.APPID);
                put("out_order_no", payInfo.getPayCode());
            }
        };

        String testCaseJson = JSON.toJSONString(testCase);
        log.info("queryPayResult,testCaseJson:"+testCaseJson);


        String sign = Sign.requestSign(testCase);
        log.info("queryPayResult,加签:"+sign);

        testCase.put("sign",sign);

        String json = JSON.toJSONString(testCase);
        log.info("queryPayResult,json:"+json);

        //调用接口,获取支付结果
        String result = HttpRequest.post(DouyinConfig.URI_QUERY_PAY_RESULT)
                .header("content-type", "application/json")
                .body(json)
                .timeout(200000)
                .execute()
                .body();

        DouyinResPayResult res= JSON.parseObject(result,DouyinResPayResult.class);
        log.info("queryPayResult,查询支付结果:"+res);

        //支付成功
        if(res.getErr_no()==0 && "SUCCESS" .equals(res.getPayment_info().getOrder_status())){
            callbackPayed(payInfo.getPayCode(),res.getOrder_id());
        }
        else {
            if(isOverThreeDays(payInfo.getCreateTime())){
                log.info("queryPayResult,超过三天未支付,设置为取消支付,getPayCode:"+payInfo.getPayCode());

                //延期的算作是 取消支付
                payInfo.setPayStatus(2);
                flowPayInfoMapper.updateById(payInfo);

            }
        }



    }

    /**
     * 超过三天
     *
     * @param timestamp 时间戳
     * @return boolean
     */
    private boolean isOverThreeDays(long timestamp) {
        long currentTime = System.currentTimeMillis();
        long difference = currentTime - timestamp;
        long threeDaysInMillis = 3 * 24 * 60 * 60 * 1000; // 三天的毫秒数

        return difference > threeDaysInMillis;
    }

    /**
     * 超过三天
     *
     * @param date 日期
     * @return boolean
     */
    private boolean isOverThreeDays(Date date) {
        return isOverThreeDays(date.getTime());
    }

}
